package cpu.footprint.ui;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cpu.footprint.R;
import cpu.footprint.adapter.CommonAdapter;
import cpu.footprint.adapter.ViewHolder;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.MyApplication;
import cpu.footprint.bean.Active;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.api.APIService;
import cpu.footprint.api.RespCallBack;
import cpu.footprint.view.XListView;
import cpu.footprint.view.photo.TouchImageActivity;

/**
 * Created by WJP on 2017/3/14.
 */
@ContentView(value = R.layout.activity_myactive)
public class MyActiveActivty extends BaseActivity implements XListView.IXListViewListener {
    private String TAG = "ActiveDetailActivty";
    @ViewInject(R.id.title_content)
    private TextView title_content;//title内容
    @ViewInject(R.id.title_menu_text)
    private TextView title_menu_text;//title功能
    @ViewInject(R.id.title_menu_image)
    private ImageView title_menu_image;//title功能
    @ViewInject(R.id.listview_active)
    private XListView listview_active;
    private User user = new User();
    private MyApplication myApplication;
    private CommonAdapter<Active> activeAdapter;//群组适配器
    private List<Active> activeList = new ArrayList<>();
    private int startCount = 1;//页码
    private static int pagerCount = 8;// 每页显示多少条数据
    private boolean isHasMore = true;
    private SpannableStringBuilder builder;
    private ForegroundColorSpan blackSpan;//ForegroundColorSpan 为文字前景色 ，BackgroundColorSpan为文字背景
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
    private SimpleDateFormat reshSdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    private Date reshDate = null;
    private Dialog mDialog;
    private int flag = 0;//(0:初始 无刷新无加载，1刷新 2加载更多)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myApplication = (MyApplication) getApplication();
        user = myApplication.getUser();
        initView();
        requestData();
    }

    private void requestData() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("from", startCount + "");
        map.put("pagerCount", pagerCount + "");
        map.put("mobilePhone", user.getMobilePhone());
        map.put("token", user.getToken());
        APIService.Post(ApiUrl.URL_LIST_MYACTIVE, map, new RespCallBack<BaseBean<Active>>(MyActiveActivty.this) {
            @Override
            public void onSuccess(BaseBean<Active> result) {
                super.onSuccess(result);
                if (result.success) {
                    if (result.datas.size() < pagerCount) {
                        isHasMore = false;
                    } else {
                        isHasMore = true;
                    }
                    if (flag == 1 || flag == 0) {
                        activeList.clear();
                    } else if (flag == 2) {
                        listview_active.setSelection(startCount - pagerCount);
                    }
                    activeList.addAll(result.datas);
                    initAdapter();
                    activeAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                onLoad();
                if (mDialog != null && mDialog.isShowing())
                    mDialog.dismiss();
            }
        });
    }

    @Event(value = {R.id.title_back})
    private void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back: {
                MyActiveActivty.this.finish();
                overridePendingTransition(0,R.anim.fade);
            }
            break;
            default:
                break;
        }
    }

    /**
     * 初始化布局
     */
    private void initView() {
        title_content.setText("我的活动");
        title_menu_image.setVisibility(View.GONE);
        title_menu_text.setVisibility(View.GONE);
        mDialog = showLoadingDialog(this);
        initAdapter();
        listview_active.setPullLoadEnable(true);
        listview_active.setPullRefreshEnable(true);
        listview_active.setXListViewListener(this);
        listview_active.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Active active = activeList.get(position - 1);
                Intent intent = new Intent(MyActiveActivty.this, ActiveDetailActivty.class);
                intent.putExtra("active", active);
                intent.putExtra("joined", true);
                startActivityForResult(intent, 2);
                overridePendingTransition(0,R.anim.fade);
            }
        });
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        activeAdapter = new CommonAdapter<Active>(MyActiveActivty.this, activeList,
                R.layout.active_item) {
            @Override
            public void convert(ViewHolder helper, final Active item,
                                int position) {
                TextView text_join = helper.getView(R.id.text_join);
                text_join.setText("退出活动");
                text_join.setTextColor(Color.RED);
                text_join.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        user = myApplication.getUser();
                        Intent intent = new Intent(MyActiveActivty.this, ActiveRecordActivity.class);
                        intent.putExtra("activeId", item.getId());
                        startActivity(intent);
                        overridePendingTransition(0,R.anim.fade);
                    }
                });
                helper.setText(R.id.text_activeName, item.getName());
                helper.setText(R.id.text_activeTime,
                        sdf.format(item.getBeginTime()) + " - " + sdf.format(item.getEndTime()));
                helper.setText(R.id.text_activitySite, item.getActivitySite());
                String description = item.getDescription();
                if (description != null) {
                    Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                    Matcher m = p.matcher(description);
                    description = m.replaceAll("");
                }
                helper.setText(R.id.text_description, "活动简介:" + description);
                TextView textView = helper.getView(R.id.text_description);
                builder = new SpannableStringBuilder(textView.getText().toString());
                blackSpan = new ForegroundColorSpan(Color.BLACK);
                builder.setSpan(blackSpan, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                textView.setText(builder);
                String imagePaths = item.getImagePaths();
                String[] imgPaths = imagePaths.split(";");
                ArrayList<String> imgArray = new ArrayList<>();
                for (int i = 0; i < imgPaths.length; i++) {
                    if (i >= 3) {
                        break;
                    }
                    imgArray.add(ApiUrl.URL_HOST + imgPaths[i]);
                }
                LinearLayout image_view = helper.getView(R.id.image_view);
                if (imgPaths.length > 0) {
                    image_view.setVisibility(View.VISIBLE);
                    ImageView[] imageViews = {helper.getView(R.id.img_1), helper.getView(R.id.img_2), helper.getView(R.id.img_3)};
                    for (int i = 0; i < imgPaths.length; i++) {
                        if (i >= 3) {
                            break;
                        }
                        Picasso.with(MyActiveActivty.this).load(ApiUrl.URL_HOST + imgPaths[i]).placeholder(R.mipmap.defaultpicture).into(imageViews[i]);
                        setOnClick(imageViews[i], imgArray, i);
                    }
                } else {
                    image_view.setVisibility(View.GONE);
                }
            }
        };
        listview_active.setAdapter(activeAdapter);
        activeAdapter.notifyDataSetChanged();
    }

    /**
     * 对图片设置点击事件-实现查看大图
     *
     * @param view
     */
    private void setOnClick(ImageView view, final ArrayList<String> imgPaths, final int index) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyActiveActivty.this, TouchImageActivity.class);
                intent.putExtra("index", index);
                intent.putStringArrayListExtra("imgs", imgPaths);
                startActivity(intent);
                overridePendingTransition(0,R.anim.fade);
            }
        });
    }

    /**
     * 重写后退函数
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            MyActiveActivty.this.finish();
            overridePendingTransition(0,R.anim.fade);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }

    /**
     * 刷新数据
     */
    @Override
    public void onRefresh() {
        flag = 1;
        startCount = 1;
        requestData();
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        if (isHasMore) {
            startCount++;
            flag = 2;
            requestData();
        } else {
            listview_active.setSelection(activeList.size() - 1);
            listview_active.pauseLoadMore();//已经到底啦
        }
    }

    /**
     * 停止刷新
     */
    private void onLoad() {
        listview_active.stopRefresh();
        listview_active.stopLoadMore();
        reshDate = new Date();
        listview_active.setRefreshTime(reshSdf.format(reshDate));
    }
}
